package com.jews.securityleam.controller;

import com.jews.securityleam.starter.base.BaseJwtUser;
import com.jews.securityleam.starter.util.SpringSecurityUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "order")
@Slf4j
public class OrderController {

    // 类似菜单的URL Code(权限编码)
    // @PreAuthorize：支持SPEL 更灵活，通过bean 动态调用方法
    @PreAuthorize(value = "hasAnyAuthority('order:getOrderList')")
    @PostMapping("getOrderList")
    public List<Order> getOrderList() {
        // 权限
        BaseJwtUser jwtUser = SpringSecurityUtils.getJwtUser();
        Integer userId = jwtUser.getUserId();

        // 查询
        List<Order> orders = getOrdersByUserId(userId);

        log.info("查询用户{}下订单数为{}", userId, orders.size());
        return orders;
    }

    @Data
    static class Order {
        private int id;
        private Integer userId;
        private String name;
    }

    /**
     * 模拟service查询数据库，然后返回订单集合
     *
     * @param userId 用户id
     * @return 用户订单集合
     */
    private List<Order> getOrdersByUserId(Integer userId) {
        List<Order> orders = new ArrayList<>();

        Order order = new Order();
        order.setId(1);
        order.setUserId(userId);
        order.setName("iPhone 100x");

        orders.add(order);
        return orders;
    }
}
